<template>
  <el-autocomplete
    ref="autocompleteRef"
    class="fi-autocomplete"
    v-model="inputValue"
    :popper-class="popperClassStr"
    :value-key="valueKey"
    v-bind="$attrs"
    v-on="$attrs"
    :fetch-suggestions="querySearch"
    clearable
    @change="handleChange"
    @select="handleSelect"
  >
    <template #default="{ item }">
      <slot name="default" :item="item">
        <span v-if="Array.isArray(displayKey) && displayKey.length > 1">
          <span v-for="(itemValue, index) in displayKey" :key="index"
            >{{ item[itemValue] }}
            <span v-if="index < displayKey.length - 1">&nbsp;</span>
          </span>
        </span>
        <span v-else>{{ item[valueKey] }}</span>
      </slot>
    </template>
    <!-- 其他自定义slot -->
    <template #prefix>
      <slot name="prefix" />
    </template>
    <template #suffix>
      <slot name="suffix" />
    </template>
    <!-- <template #prepend>
      <slot name="prepend" />
    </template>
    <template #append>
      <slot name="append" />
    </template> -->
    <template #loading>
      <slot name="loading" />
    </template>
  </el-autocomplete>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed, PropType, watch, onUnmounted } from 'vue'
// import { apiRequestPost } from '@/api/globalApi.js'
import _ from 'lodash'
import { useRoute } from 'vue-router'
const route = useRoute()

const props = defineProps({
  // apiUrl: {
  //   type: String,
  //   default: '',
  // },
  // apiParams: {
  //   type: Object,
  //   default: () => ({
  //     current: 1,
  //     size: 10,
  //   }),
  // },
  // pageSize: {
  //   type: Number,
  //   default: 10,
  // },
  popperClass: {
    type: String,
    default: 'fi-autocomplete-popper-class',
  },
  // 展示列表数据集合
  options: {
    type: Array,
    default: () => [],
  },
  // 是否启用分页
  usePagination: {
    type: Boolean,
    default: false, // 默认情况下不启用分页
  },
  modelValue: {
    type: String,
    default: '',
  },
  // 输入建议对象中用于显示的键名
  valueKey: {
    type: String,
    default: 'value',
  },
  // 搜索对象的属性的值，或集合
  displayKey: {
    type: [String, Array] as PropType<string | string[]>,
    default: 'label',
  },
  // 展示对象的属性值或集合, 如果是集合则用 - 分割
  // displayKey: {
  //   type: String,
  //   default: [String, Array] as PropType<string | string[]>,
  // },
})
const autocompleteRef = ref(null)
const emits = defineEmits(['change', 'select', 'update:options', 'load-more', 'update:modelValue'])
// const state = reactive({
//   query: {
//     current: 1,
//     size: props.pageSize,
//   },
//   dataList: [],
// })
const popperClassStr = computed(() => {
  let num = Math.floor(Math.random() * 1001)
  return `${props.popperClass}-${route.name as string}` + num
})
const optionsTemp = ref(props.options)
watch(
  () => props.options,
  (newValue, oldValue) => {
    if (newValue.length > 0) {
      optionsTemp.value = newValue
      autocompleteRef.value.suggestions = newValue
      // state.dataList = newValue
    }
    emits('update:options', newValue)
  },
  { deep: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
// const inputValue = ref(props.modelValue)
const inputValue: any = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})

const handleSelect = (item: Record<string, any>) => {
  emits('update:modelValue', item[props.valueKey])
  emits('select', item)
}
const handleChange = (item: any) => {
  emits('change', item)
}
let timeout: ReturnType<typeof setTimeout>
const querySearch = (queryString: string, cb: (arg: any) => void) => {
  const results = queryString ? optionsTemp.value.filter(createFilter(queryString)) : optionsTemp.value
  clearTimeout(timeout)
  timeout = setTimeout(() => {
    cb(results)
  }, 300)
}
const createFilter = (queryString: string) => {
  return (restaurant: any) => {
    const searchValue = queryString.toLowerCase()
    const keysToSearch = new Set<string>()

    // 添加props.valueKey到集合中
    if (Array.isArray(props.displayKey) && props.displayKey.length > 0) {
      props.displayKey.forEach((key) => keysToSearch.add(key))
    } else {
      keysToSearch.add(props.displayKey)
    }
    // if (props.valueKey) {
    //   keysToSearch.add(props.valueKey)
    // }
    // if (props.valueKey2) {
    //   keysToSearch.add(props.valueKey2)
    // }

    // // 如果props.valueKeyArr存在且不为空，将其内容添加到集合中
    // if (Array.isArray(props.valueKeyArr)) {
    //   props.valueKeyArr.forEach((key) => keysToSearch.add(key))
    // }

    // 遍历所有需要检查的key，判断是否匹配
    return Array.from(keysToSearch).some((key) => {
      return restaurant[key]?.toString().toLowerCase().includes(searchValue)
    })
  }
}
// const loadMore = (type?: string, columnsVal?: any) => {
//   // state.query.current = pageConfig.currentPage
//   // isTableLoading.value = true
//   // if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
//   if (type === 'more') state.query.current++
//   apiRequestPost(props.apiUrl, state.query)
//     .then((res) => {
//       // isTableLoading.value = false
//       if (res.data.success) {
//         if (type === 'more') {
//           // state.dataList = [...state.dataList, ...res.data.data.result]
//           // 优化：检查新数据是否与已有数据不同，避免重复添加
//           const newData = res.data.data.result.filter(
//             (item) => !state.dataList.some((existingItem) => existingItem.id === item.id)
//           )
//           state.dataList = [...state.dataList, ...newData]
//           autocompleteRef.value.suggestions = state.dataList
//         } else {
//           state.dataList = res.data.data.result
//         }
//         // console.log('--------000000', state.dataList.length)
//         // querySearch(inputValue)
//       }
//     })
//     .catch((error: any) => {
//       // isTableLoading.value = false
//       // 处理错误
//     })
// }
const handleScroll = _.debounce((e) => {
  console.log('handleScroll')
  const { scrollTop, scrollHeight, clientHeight } = e.target
  console.log(scrollTop + clientHeight, '======================')
  console.log(scrollHeight, 'scrollHeight')
  if (scrollTop + clientHeight >= scrollHeight - 10) {
    emits('load-more')
    // loadMore('more')
  }
}, 300)
onMounted(() => {
  // if (props.options && props.options.length > 0) {
  //   state.dataList = props.options
  // } else {
  //   state.query = { ...props.apiParams, ...state.query }
  //   state.query[props.queryKey] = ''
  //   if (props.apiUrl) {
  //     loadMore()
  //   }
  // const autocomplete = document.querySelector('.el-autocomplete-suggestion__wrap')
  // autocomplete.addEventListener('scroll', handleScroll)
  // }
  // 如果启动分页，则监听滚动事件
  if (props.usePagination) {
    // const autocomplete = document.querySelector('.el-autocomplete-suggestion__wrap')
    const autocomplete = document.querySelector(`.${popperClassStr.value} .el-autocomplete-suggestion__wrap`)
    if (autocomplete) {
      autocomplete.addEventListener('scroll', handleScroll)
    }
  }
})
onUnmounted(() => {
  if (props.usePagination) {
    // const autocomplete = document.querySelector('.el-autocomplete-suggestion__wrap')
    const autocomplete = document.querySelector(`.${popperClassStr.value} .el-autocomplete-suggestion__wrap`)
    // 检查事件处理器是否存在
    if (handleScroll && autocomplete) {
      autocomplete.removeEventListener('scroll', handleScroll)
    }
  }
})
</script>
<style lang="less" scoped>
.fi-autocomplete {
  ::v-deep(.el-autocomplete-suggestion) {
    background: red;
    li:hover {
      background-color: var(--el-color-primary-light-9) !important;
    }
  }
}
</style>
